import type { Context } from 'elysia';
import { eq, desc, asc, like, and, or, count } from 'drizzle-orm';
import { db } from '../db';
import { cases } from '../db/schema';
import { successResponse, errorResponse, ApiError, asyncHandler, Logger } from '../utils/response';
import type { AuthContext } from '../middleware/auth';

// 获取所有应用场景标签
export const getApplicationScenes = asyncHandler(async ({ query, set }: Context) => {
    const { industryId, search } = query as any;

    let conditions = [eq(cases.status, 'active')];
    
    if (industryId) {
      conditions.push(eq(cases.industryId, industryId));
    }

    if (search) {
      conditions.push(
        or(
          like(cases.title, `%${search}%`),
          like(cases.description, `%${search}%`)
        )
      );
    }

    const whereClause = conditions.length > 0 ? and(...conditions) : undefined;

    const result = await db.select({ applicationScenes: cases.applicationScenes })
      .from(cases)
      .where(whereClause);

    const allScenes = new Set<string>();
    result.forEach(item => {
      if (item.applicationScenes) {
        try {
          const scenes = JSON.parse(item.applicationScenes);
          if (Array.isArray(scenes)) {
            scenes.forEach(scene => {
              if (scene && scene.trim()) {
                allScenes.add(scene.trim());
              }
            });
          }
        } catch (e) {
          // 忽略解析错误
        }
      }
    });

    const scenes = Array.from(allScenes)
      .filter(Boolean)
      .sort();

    Logger.info('获取应用场景标签', { 
      scenesCount: scenes.length, 
      industryId: industryId || 'all'
    });

    return successResponse(scenes, '获取应用场景标签成功');
});

// 获取热门应用场景标签（按使用频率排序）
export const getPopularApplicationScenes = asyncHandler(async ({ query, set }: Context) => {
    const { industryId, limit = '20' } = query as any;
    const limitNum = parseInt(limit);

    let conditions = [eq(cases.status, 'active')];
    
    if (industryId) {
      conditions.push(eq(cases.industryId, industryId));
    }

    const whereClause = conditions.length > 0 ? and(...conditions) : undefined;

    const result = await db.select({ applicationScenes: cases.applicationScenes })
      .from(cases)
      .where(whereClause);

    const sceneCount = new Map<string, number>();
    
    result.forEach(item => {
      if (item.applicationScenes) {
        try {
          const scenes = JSON.parse(item.applicationScenes);
          if (Array.isArray(scenes)) {
            scenes.forEach(scene => {
              if (scene && scene.trim()) {
                const trimmedScene = scene.trim();
                sceneCount.set(trimmedScene, (sceneCount.get(trimmedScene) || 0) + 1);
              }
            });
          }
        } catch (e) {
          // 忽略解析错误
        }
      }
    });

    const popularScenes = Array.from(sceneCount.entries())
      .sort((a, b) => b[1] - a[1]) // 按使用频率降序排序
      .slice(0, limitNum)
      .map(([scene, count]) => ({ scene, count }));

    Logger.info('获取热门应用场景标签', { 
      popularScenesCount: popularScenes.length, 
      industryId: industryId || 'all'
    });

    return successResponse(popularScenes, '获取热门应用场景标签成功');
});

// 根据应用场景搜索案例
export const searchCasesByApplicationScene = asyncHandler(async ({ query, set }: Context) => {
    const {
      scene,
      industryId,
      page = '1',
      limit = '10'
    } = query as any;

    if (!scene) {
      throw ApiError.validation('应用场景参数为必填项');
    }

    const pageNum = parseInt(page);
    const limitNum = parseInt(limit);
    const offset = (pageNum - 1) * limitNum;

    let conditions = [
      eq(cases.status, 'active'),
      like(cases.applicationScenes, `%"${scene}"%`) // 搜索JSON数组中包含该场景的案例
    ];
    
    if (industryId) {
      conditions.push(eq(cases.industryId, industryId));
    }

    const whereClause = and(...conditions);

    const [caseList, [{ total }]] = await Promise.all([
      db.select()
        .from(cases)
        .where(whereClause)
        .orderBy(desc(cases.createdAt))
        .limit(limitNum)
        .offset(offset),
      db.select({ total: count() })
        .from(cases)
        .where(whereClause)
    ]);

    const processedCases = caseList.map(caseItem => ({
      ...caseItem,
      images: JSON.parse(caseItem.images || '[]'),
      tags: JSON.parse(caseItem.tags || '[]'),
      applicationScenes: JSON.parse(caseItem.applicationScenes || '[]'),
      testimonial: caseItem.testimonial ? JSON.parse(caseItem.testimonial) : null,
      services: JSON.parse(caseItem.services || '[]'),
      highlights: JSON.parse(caseItem.highlights || '[]'),
      detailImages: JSON.parse(caseItem.detailImages || '[]')
    }));

    Logger.info('根据应用场景搜索案例', {
      scene,
      industryId: industryId || 'all',
      total,
      page: pageNum,
      limit: limitNum
    });

    return successResponse({
      cases: processedCases,
      pagination: {
        total,
        page: pageNum,
        limit: limitNum,
        totalPages: Math.ceil(total / limitNum)
      }
    }, '根据应用场景搜索案例成功');
});

// 获取应用场景统计信息
export const getApplicationSceneStats = asyncHandler(async ({ query, set }: Context) => {
    const { industryId } = query as any;

    let conditions = [eq(cases.status, 'active')];
    
    if (industryId) {
      conditions.push(eq(cases.industryId, industryId));
    }

    const whereClause = conditions.length > 0 ? and(...conditions) : undefined;

    const result = await db.select({ 
      applicationScenes: cases.applicationScenes,
      industryId: cases.industryId
    })
      .from(cases)
      .where(whereClause);

    const sceneStats = new Map<string, { count: number; industries: Set<number> }>();
    
    result.forEach(item => {
      if (item.applicationScenes) {
        try {
          const scenes = JSON.parse(item.applicationScenes);
          if (Array.isArray(scenes)) {
            scenes.forEach(scene => {
              if (scene && scene.trim()) {
                const trimmedScene = scene.trim();
                if (!sceneStats.has(trimmedScene)) {
                  sceneStats.set(trimmedScene, { count: 0, industries: new Set() });
                }
                const stats = sceneStats.get(trimmedScene)!;
                stats.count++;
                stats.industries.add(item.industryId);
              }
            });
          }
        } catch (e) {
          // 忽略解析错误
        }
      }
    });

    const statsArray = Array.from(sceneStats.entries())
      .map(([scene, stats]) => ({
        scene,
        caseCount: stats.count,
        industryCount: stats.industries.size,
        industries: Array.from(stats.industries)
      }))
      .sort((a, b) => b.caseCount - a.caseCount);

    Logger.info('获取应用场景统计信息', { 
      totalScenes: statsArray.length,
      industryId: industryId || 'all'
    });

    return successResponse({
      totalScenes: statsArray.length,
      scenes: statsArray
    }, '获取应用场景统计信息成功');
});